package com.wifi.mydlq.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class TokenUtilService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 存入Redis的Token键的前缀
     */
    private static final String IDEMPOTENT_TOKEN_PREFIX = "idempotent_token:";

    public String generateToken(String value) {
        String token = UUID.randomUUID().toString();
        String key = IDEMPOTENT_TOKEN_PREFIX + token;
        stringRedisTemplate.opsForValue().set(key, value, 5, TimeUnit.MINUTES);
        return token;
    }

    public boolean validToken(String token, String value) {
        String luaScript = "if redis.call('get', KEYS[1]) == KEYS[2] " +
                "then return redis.call('del', KEYS[1])" +
                "else return 0 end";
        RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript, Long.class);
        String key = IDEMPOTENT_TOKEN_PREFIX + token;
        Long result = stringRedisTemplate.execute(redisScript, Arrays.asList(key, value));
        if (result != null && result != 0L) {
            System.out.println("验证 token 成功： " + token);
            return true;
        }
        System.out.println("验证 token 失败： " + token);
        return false;
    }
}
